package com.stb.server.guice;

import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.stb.server.RequestInjectedService;

@Singleton
@SuppressWarnings("serial")
public class GuiceRemoteServiceServlet extends RemoteServiceServlet {
	@Inject
	private Injector injector;

	@Override
	public String processCall(String payload) throws SerializationException {
		try {
			RPCRequest req = RPC.decodeRequest(payload, null, this);
			RequestInjectedService service = getServiceInstance(req.getMethod().getDeclaringClass());
			service.setRequest(getThreadLocalRequest());
			return RPC.invokeAndEncodeResponse(service, req.getMethod(), req.getParameters(), req.getSerializationPolicy());
		} catch (IncompatibleRemoteServiceException e) {
			log("IncompatibleRemoteServiceException in the processCall(String) method.", e);
			return RPC.encodeResponseForFailure(null, e);
		}
	}

	private RequestInjectedService getServiceInstance(Class<?> serviceClass) {
		return (RequestInjectedService) injector.getInstance(serviceClass);
	}
}